package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VoiceApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Voice;
import com.tanhua.model.vo.ErrorResult;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.tanhua.model.vo.VoiceVo;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import com.tanhua.server.interceptor.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * @Description:
 * @Create by: wanglei
 * @Date: 2021/11/6 18:29
 */
//桃花传音相关
@Service
public class VoiceService {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VoiceApi voiceApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisService redisService;  //redis工具类

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //保存当前用户发布的语音
    public void saveVoice(MultipartFile soundFile) throws IOException {
        //进行非空判断
        if(soundFile.isEmpty()) {
            throw new BusinessException(ErrorResult.builder().errMessage("请发布正确语音内容，不要为空").build());
        }
        //获取当前时间距离凌晨的毫秒数
        Long nowToNextDaySeconds = redisService.getNowToNextDaySeconds();
        //查询redis，看用户当天上传了几条语音了
        //首先判断,redis中是否有值
        String saveVoiceCount = (String) redisTemplate.opsForHash().get(Constants.VOICE_SAVE_COUNT,String.valueOf(UserHolder.getUserId()));
        if (StringUtils.isEmpty(saveVoiceCount)){
            //为空，创建,并且设置销毁时间为第二天凌晨。
            redisTemplate.opsForHash().put(Constants.VOICE_SAVE_COUNT,String.valueOf(UserHolder.getUserId()),String.valueOf(1));
            //设置过期时间
            redisTemplate.expire(Constants.VOICE_SAVE_COUNT,nowToNextDaySeconds,TimeUnit.SECONDS);
        }else{
            //不为空，判断值的大小
            Integer count = Integer.valueOf(saveVoiceCount);
            if (count > 2){
                //条数超过了，限制，直接提醒
                throw new BusinessException(ErrorResult.builder().errMessage("大哥，今日发布的语音数量封顶了。").build());
            }else{
                //条数没有超过限制，给条数加1
                redisTemplate.opsForHash().put(Constants.VOICE_SAVE_COUNT,String.valueOf(UserHolder.getUserId()),String.valueOf(count+1));
            }
        }
        //1、将语音上传到FastDFS,获取访问URL
        String filename = soundFile.getOriginalFilename();  // abc.mp3
        filename = filename.substring(filename.lastIndexOf(".")+1);
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), filename, null);
        String voiceUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //构建voice对象
        Voice voice = new Voice();
        voice.setVoiceUrl(voiceUrl);
        voice.setUserId(UserHolder.getUserId());
        voice.setCreated(System.currentTimeMillis());
        //调用api保存，并返回id
        String id = voiceApi.saveVoice(voice);
        //如果保存失败，给用户提示
        if(StringUtils.isEmpty(id)) {
            throw new BusinessException(ErrorResult.builder().errMessage("当前繁忙，请稍后再试").build());
        }
    }

    //随机推荐语音
    public VoiceVo getRandomVoice() {
        //获取当前时间距离凌晨的毫秒数
        Long nowToNextDaySeconds = redisService.getNowToNextDaySeconds();
        //查询redis，看用户当天查看了几条语音了
        //首先判断,redis中是否有值
        String saveVoiceCount = (String) redisTemplate.opsForHash().get(Constants.VOICE_SEE_COUNT,String.valueOf(UserHolder.getUserId()));
        //收听语音的次数
        Integer count = 0;
        if (StringUtils.isEmpty(saveVoiceCount)){
            //为空，创建,并且设置销毁时间为第二天凌晨。
            redisTemplate.opsForHash().put(Constants.VOICE_SEE_COUNT,String.valueOf(UserHolder.getUserId()),String.valueOf(1));
            //设置过期时间
            redisTemplate.expire(Constants.VOICE_SEE_COUNT,nowToNextDaySeconds,TimeUnit.SECONDS);
        }else{
            //不为空，判断值的大小
            count = Integer.valueOf(saveVoiceCount);
            if (count > 2){
                //今日查看，条数超过了限制，直接提醒
                throw new BusinessException(ErrorResult.builder().errMessage("大哥，您今日收听的语音到头了，明日再来。").build());
            }else{
                //条数没有超过限制，给条数加1
                redisTemplate.opsForHash().put(Constants.VOICE_SEE_COUNT,String.valueOf(UserHolder.getUserId()),String.valueOf(count+1));
            }
        }
        //调用api,获取随机推荐
        Voice voice = voiceApi.randomShow();
        if (voice == null){
            throw new BusinessException(ErrorResult.builder().errMessage("大哥，系统的语音让你看光了").build());
        }
        Long userId = voice.getUserId();
        //获取userInfo对象
        UserInfo userInfo = userInfoApi.findById(userId);
        //组装vo对象
        VoiceVo voiceVo = VoiceVo.init(userInfo, voice);
        //设置剩余收听次数
        voiceVo.setRemainingTimes(3-count);
        //调用api,删除这条语音
        voiceApi.delete(userId,voice.getTid());
        //返回结果
        return voiceVo;
    }
}
